package com.situ.mall.service.impl;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.situ.mall.entity.Result;
import com.situ.mall.entity.User;
import com.situ.mall.mapper.UserMapper;
import com.situ.mall.service.IUserService;

@Service
public class UserServiceImpl implements IUserService{
	@Autowired
	private UserMapper userMapper;

// 0.测试
	@Override
	public List<User> selectAll() {
		return userMapper.selectAll();
	}
//后台
// 1.每页信息
	@Override
	public Result selectByPage(Integer page, Integer limit) {
		//1.总页数
		int count = userMapper.getTotalPage();
		
		// 2.每页信息
		int offset = (page-1)*limit;
		List<User> list = userMapper.selectByPage(offset, limit);
		
		System.out.println(count);
		System.out.println(list);
		
		return Result.success("", list, count);
	}
	
//2.删除 单个
	@Override
	public Result deleteById(Integer id) {
		System.out.println("UserServiceImpl.deleteById()");
		
		Integer count = userMapper.deleteById(id);
		return count>0 ? Result.success("删除成功") : Result.error("删除失败");
	}


//3.批量删除
	@Override
	public Result deleteAll(Integer[] ids) {
		System.out.println("UserServiceImpl.deleteAll()");
		
		//计数，总共删除的此时=ids的长度，删除成功，否则失败
		int count  = 0;
		for (Integer id : ids) {
			int ever = userMapper.deleteAll(id);
			count+=ever;
		}
		return count==ids.length ? Result.success("批量删除成功"):Result.error("批量删除失败");
	}


//4.添加
	@Override
	public Result insert(User user) {
		System.out.println("UserServiceImpl.insert()");
		
		int count = userMapper.insert(user);
		return count>0? Result.success("添加成功") : Result.error("添加失败");
	}
	
//5.导出Excel表格
	@Override
	public void exportExcel(HttpServletResponse response) {
		System.out.println("UserServiceImpl.exportExcel()");
		
			XSSFWorkbook workbook = new XSSFWorkbook();
			XSSFSheet sheet = workbook.createSheet("用户列表");
			// 设置默认的列宽
			sheet.setDefaultColumnWidth(25);
			// 创建合并单元格对象
			CellRangeAddress cellRangeAddress = new CellRangeAddress(2, 4, 1, 4);
			sheet.addMergedRegion(cellRangeAddress);
			// 创建行：Row
			XSSFRow row = sheet.createRow(2);
			// 创建单元格：Cell (这个cell就是合并单元格的cell)
			XSSFCell cell = row.createCell(1);
			// 设置单元格的样式
			XSSFCellStyle style = workbook.createCellStyle();
			style.setAlignment(XSSFCellStyle.ALIGN_CENTER);// 水平居中
			style.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);// 垂直居中
			cell.setCellStyle(style);
			cell.setCellValue("用户列表");
			// 创建要输出的列
			String[] array = {"编号", "用户名", "手机号", "邮编"};
			XSSFRow rowHead = sheet.createRow(5);
			for (int i = 0; i < array.length; i++) {
				XSSFCell cellHead = rowHead.createCell(i + 1);
				cellHead.setCellValue(array[i]);
			}
			
			List<User> list = userMapper.selectAll();
			// 这个i是变量控制行
			for (int i = 0; i < list.size(); i++) {
				User user = list.get(i);
				XSSFRow userRow = sheet.createRow(6 + i);
				
				XSSFCell cellId = userRow.createCell(1);
				cellId.setCellValue(user.getId());
				
				XSSFCell cellName = userRow.createCell(2);
				cellName.setCellValue(user.getUsername());
				
				XSSFCell cellPhone = userRow.createCell(3);
				cellPhone.setCellValue(user.getPhone());
				
				XSSFCell cellEmail = userRow.createCell(4);
				cellEmail.setCellValue(user.getEmail());
			}
			
			// *****  以附件的形式返回给浏览器，要借助response。。。。返回 让你选择存在什么地方 那个框
									//.xlsx  每种文档接口不一样，改文档接口
					//https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types
			response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
			ServletOutputStream outputStream = null;
			try {
				response.setHeader("Content-Disposition", 
						"attachment;filename=" + new String("用户列表.xlsx".getBytes(), "ISO-8859-1"));
				outputStream = response.getOutputStream();
				workbook.write(outputStream);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if (workbook != null) {
					try {
						workbook.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
					if (outputStream != null) {
						try {
							outputStream.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
			}
		
		
	}

	
//前台  
	// 1.验证登陆信息   账户密码是否正确
	@Override
	public User login(User fromUser) {
		System.out.println("UserServiceImpl.login()");
	
		User user = userMapper.login(fromUser);
		System.out.println(user);
		return user; 
		
		
	}
	


}
